package org.batallademusica.dao;

import java.util.HashMap;
import java.util.Map;

import javax.persistence.EntityManager;

public class EntityManagerRepository {
	private Map<Thread,RunningEntityManager> mapaEM;
	private static final long RUNNINGENTITYMANATER_TTL=30*60*1000;//30min.
	private static EntityManagerRepository instancia;
	
	public static EntityManagerRepository getInstance(){
		if(instancia==null) instancia=new EntityManagerRepository();
		return instancia;
	}
	private EntityManagerRepository(){
		this.mapaEM=new HashMap<Thread,RunningEntityManager>();
	}
	
	public EntityManager recuperarEntityManager(){
		RunningEntityManager rem=null;
		if(null==(rem=this.mapaEM.get(Thread.currentThread()))
			|| isCaducado(rem)){
			rem=new RunningEntityManager(EntityManagerFactorySingleton.getInstance().getEntityManagerFactory().createEntityManager());
			this.mapaEM.put(Thread.currentThread(), rem);
		}
		return rem.getEntityManager();
	}
	
	public void cerrarEntityManager(){
		RunningEntityManager rem=this.mapaEM.remove(Thread.currentThread());
		if(rem!=null && rem.getEntityManager().isOpen()) rem.getEntityManager().close();
	}
	
	public void chequearTTL(){
		for(Map.Entry<Thread,RunningEntityManager> entrada : this.mapaEM.entrySet()){
			if(isCaducado(entrada.getValue())){ 
				entrada.getValue().getEntityManager().close();
				this.mapaEM.remove(entrada.getKey());
			}
		}
	}
	
	private boolean isCaducado(RunningEntityManager rem){
		return System.currentTimeMillis()-rem.getUltimoAcceso()>RUNNINGENTITYMANATER_TTL;
	}
	
	/**
	 * Por si acaso. 
	 */
	public void finalize(){
		for(Map.Entry<Thread,RunningEntityManager> entrada : this.mapaEM.entrySet()){
			if(entrada.getValue().getEntityManager().isOpen()) entrada.getValue().getEntityManager().close();
		}
	}
	
}
